package DSPackage;

import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import jade.Boot;
import jade.core.*;
import jade.core.ProfileImpl;
import jade.core.Runtime;
import jade.wrapper.*;

/**
 * 
 */
public class DS implements ClientDS {
 private String appName = null;
    private int aCnt = 0;
    private String maxAvBW = "0";

    private static ContainerController cc;
    private AgentController ac = null;

    private static Runtime runtime = Runtime.instance();

    public DS() {

    }

     /**
     * Method used by Client to get the host name of the file
     * server
     */
    public String getApp(String appName) throws RemoteException {
        String name = "DS" + aCnt;
        aCnt++;

        Object[] argument = new Object[3];
        argument[0] = this;
        argument[1] = appName;
        argument[2] = cc;

        try {
            ac = cc.createNewAgent(name, ControlAgent.class.getName(), argument);
            ac.start();
        } catch (Exception e) {
            System.err.println("Problem creating new agent");
            e.printStackTrace();
        }

        waiting();

        this.appName = maxAvBW;
        return this.appName;
    }

    private synchronized void waiting() {
        try {
            wait();
        } catch (Exception e) {
            System.err.println("Error while waiting for DS agent.");
        }
    }

    public synchronized void restart(String maxBW) {
        maxAvBW = maxBW;
        notify();
    }

    public static void main(String args[]) {

        try {
            ProfileImpl p = new ProfileImpl();
            p.setParameter(p.CONTAINER_NAME, "DS");
            
            cc = runtime.createMainContainer(p);

            // Setting up server connection to Client
            DS DLserver = new DS();
            ClientDS stub = (ClientDS) UnicastRemoteObject.
                    exportObject(DLserver, 0);

            Registry reg = LocateRegistry.getRegistry(2001);
            reg.rebind("ClientDS", stub);

            System.err.println("Download server ready");

        } catch (Exception e) {
            System.out.println("Download server exception: "
                    + e.toString());
        }
    }
}
